package com.ygxsk.carhome.ui.care;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.kongzue.dialogx.dialogs.PopTip;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.constant.RefreshState;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.enumwrap.CallHistoryBusinessType;
import com.ygxsk.carhome.enumwrap.CardAuditStatus;
import com.ygxsk.carhome.enumwrap.CouponAuditStatus;
import com.ygxsk.carhome.enumwrap.CouponOrPackType;
import com.ygxsk.carhome.event.EventCardMain;
import com.ygxsk.carhome.listener.DoSomeThingListener;
import com.ygxsk.carhome.response.CouponCustomerVo;
import com.ygxsk.carhome.response.CouponCustomerVoCopy;
import com.ygxsk.carhome.response.CouponCustomerVoOutSide;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.ui.BaseImmersionFragment;
import com.ygxsk.carhome.ui.adapter.CardToBeReviewedAdapter;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.integrated.retrofit.Parameterkey;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link CardToBeReviewedListFragment#newInstance} factory method to
 * create an instance of this fragment. 2024年2月27日16:52:443优惠券改造，这是待审核界面。
 */
public class CardToBeReviewedListFragment extends BaseImmersionFragment {


    @BindView(R.id.refreshlayoutintobecardfragment)
    SmartRefreshLayout refreshLayoutInCardFragment;

    @BindView(R.id.recyclerviewintobecardfragment)
    RecyclerView recyclerViewInCardFragment;
//    RecyclerViewAtViewPager2 recyclerViewInCardFragment;


    //该页面的优惠券发放的历史记录
    private ArrayList<CouponCustomerVo> mDataResources = new ArrayList<>();

    //待核销的历史记录
    private CardToBeReviewedAdapter cardToBeReviewedAdapter;
    /**
     * 最后一条上传的id的信息内容
     */
    private int pagination_upLoad = Parameterkey.pageNum_default_first;


    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_FLAG_JUMPFROM_WHERE = "flag_jumpfrom_where";
    private static final String ARG_INDEXPOSITION = "indexposition";
    //
    private static final String ARG_AUDIT_STATUS = "arg_audit_status";
    private static final String ARG_INDEXNAME = "indexname";

    // TODO: Rename and change types of parameters
    private int flag_jumpfrom_where;
    //携带标志内容
    private String indexPosition;
    //直接采用从外侧携带状态值的逻辑：  0, //审核状态 0：待审核 1：审核通过 2：审核不通过
    private int auditStatus_form_tab_list;
    private String indexName;

    //该优惠券的详细信息
//    private MaterialDialog materialDialogCustomView;

    public CardToBeReviewedListFragment() {
        // Required empty public constructor
    }

    // TODO: Rename and change types and number of parameters
    public static CardToBeReviewedListFragment newInstance(int flag_jumpfrom_where, String indexPosition, int auditStatus, String indexName) {

        CardToBeReviewedListFragment fragment = new CardToBeReviewedListFragment();

        Bundle args = new Bundle();

        args.putInt(ARG_FLAG_JUMPFROM_WHERE, flag_jumpfrom_where);

        args.putString(ARG_INDEXPOSITION, indexPosition);
        args.putInt(ARG_AUDIT_STATUS, auditStatus);//新增 2024-2-28 18:23:17
        args.putString(ARG_INDEXNAME, indexName);

        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mFragmentInstance = this;
        mActivityInstance = this.getActivity();

        if (getArguments() != null) {

            flag_jumpfrom_where = getArguments().getInt(ARG_FLAG_JUMPFROM_WHERE);

            indexPosition = getArguments().getString(ARG_INDEXPOSITION);
            auditStatus_form_tab_list = getArguments().getInt(ARG_AUDIT_STATUS);
            indexName = getArguments().getString(ARG_INDEXNAME);

        }

        //要刷新？
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    }


    @Override
    protected void initView() {
        super.initView();

        //------------------------------------------------------------------------------------------------------------------------------------------
        //布局的适配器填充，下拉刷新等等；
        LinearLayoutManager layoutManager = new LinearLayoutManager(mFragmentInstance.getContext(), LinearLayoutManager.VERTICAL, false);
//        recyclerViewInCardFragment.setLayoutManager(new MyLinearLayoutManager(this.getContext()));
        recyclerViewInCardFragment.setLayoutManager(layoutManager);
        cardToBeReviewedAdapter = new CardToBeReviewedAdapter(flag_jumpfrom_where, R.layout.fragment_card_tobereviewed_adapter, mDataResources);
        recyclerViewInCardFragment.setAdapter(cardToBeReviewedAdapter);
//        recyclerViewInCardFragment.setNestedScrollingEnabled(true);//支持嵌套滚动
        cardToBeReviewedAdapter.notifyDataSetChanged();

        //这里添加一个header展示发放记录的；
        //smartGoItemAdapter.removeAllHeaderView();
        //smartGoItemAdapter.addHeaderView(getHeaderView(recyclerViewInSmartGo));

        cardToBeReviewedAdapter.setOnItemClickListener(new com.chad.library.adapter.base.listener.OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                //如果是餐券的发放的过来，就没有点击事件？
                CouponCustomerVo couponCustomerVo = (CouponCustomerVo) adapter.getItem(position);

                method_click_onitem(couponCustomerVo);

            }
        });

        cardToBeReviewedAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                //仅仅复制手机号码
                CouponCustomerVo couponCustomerVo = (CouponCustomerVo) adapter.getItem(position);

                switch (view.getId()) {

                    case R.id.imagerightinfoclicktobe: {

                        method_click_onitem(couponCustomerVo);

                        break;
                    }

//                    case R.id.imagerightinfoclick: {//查看优惠券的发送原因
//
//                        if (couponCustomerVo != null) {
//
////                            String couponName = couponCustomerVo.getCouponName();
////                            String explain = couponCustomerVo.getExplain();
//                            //CommUtils.alertMaterialDialog(mActivityInstance, couponCustomerVo.getCouponName(), couponCustomerVo.getExplain());
////                            function_show_dialog_seeReason(couponCustomerVo);
////                            function_show_dialog_seeReason(couponCustomerVo);
//
//
//                            CommUtils.checkMaterialDialog(materialDialogCustomView);
//
//                            materialDialogCustomView = CommTools.function_show_dialog_seeReason(flag_jumpfrom_where, //
//                                    mActivityInstance,//
//                                    mActivityInstance,//
//                                    couponCustomerVo, //
//                                    new DoSomeThingListener() {
//                                        @Override
//                                        public void doSomeThing() {
//
//                                            if (materialDialogCustomView != null) {
//                                                materialDialogCustomView.dismiss();
//                                                materialDialogCustomView = null;
//                                            }
//
//                                        }
//                                    });
//
//
//                        }
//
//                        break;
//                    }

//                    case R.id.textviewcarsendreason: {//查看原因的文字
//
//                        if (couponCustomerVo != null) {
//
////                            String explain = couponCustomerVo.getExplain();
////                            String couponName = couponCustomerVo.getCouponName();
////                            CommUtils.alertMaterialDialog(mActivityInstance, couponCustomerVo.getCouponName(), couponCustomerVo.getExplain());
//
//                            function_show_dialog_seeReason(couponCustomerVo);
//
//                        }
//
//                        break;
//                    }

                    case R.id.textvieweditviewphonetobe: {//拨打电话的能力

                        if (couponCustomerVo != null) {

                            clickButton_toCallPhone(mActivityInstance, couponCustomerVo.getPhone(), CallHistoryBusinessType.BUSINESSTYPE_9.getIndex());

                            //同时复制
//                    if (!TextUtils.isEmpty(couponCustomerVo.getPhone())) {
//                        CommUtils.methodCopyClip(couponCustomerVo.getPhone(),true);
//                    }else{
//                        ToastUtils.showShort(R.string.hasfailgetphonenumber);
//                    }

                        }

                        break;
                    }

//                    case R.id.roundtextViewDoVerifyMoreItems: {//【批量审核】按钮
//
//                        //历史记录页面，做批量审核。
//                        method_go_history(true, String.valueOf(couponCustomerVo.getCouponPackId()));
//
//                        break;
//                    }

                    case R.id.roundtextViewDotobe: {//审核按钮

                        if (couponCustomerVo != null) {

                            method_click_onitem(couponCustomerVo);

//                            CommUtils.checkDialog(mAlertView);
//                            mAlertView = new AlertView(StringUtils.getString(R.string.clearaddorsubmitsuretitletips), //提示
//                                    StringUtils.getString(R.string.submit_consign_verify_message_sure),//提示内容 确定审核通过
//                                    StringUtils.getString(R.string.clearcachecancel), //取消
//                                    new String[]{StringUtils.getString(R.string.clearaddorsubmitsure)},//确定
//                                    null, mActivityInstance, AlertView.Style.Alert, new OnItemClickListener() {//
//                                @Override
//                                public void onItemClick(Object o, int position) {
//                                    if (position != AlertView.CANCELPOSITION) {
//                                        //"couponCustomerId": 62986, //发放的优惠券记录主键Id
//                                        //"couponId": 1, //优惠券主键Id
//                                        //"auditStatus": 1 //审核状态 0：待审核 1：审核通过 2：审核不通过
//                                        method_gainVerifySubmitInfo_upLoad(couponCustomerVo.getCouponCustomerId(), couponCustomerVo.getCouponId(), couponCustomerVo.getAuditStatus());
//                                    }
//                                }
//                            });
//                            mAlertView.setCancelable(true);
//                            mAlertView.show();

                        }

                        break;
                    }

                    default:
                        break;
                }

            }
        });


        if (refreshLayoutInCardFragment != null) {

            refreshLayoutInCardFragment.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
                @Override
                public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

                    refreshLayout.getLayout().post(new Runnable() {
                        @Override
                        public void run() {

                            //区分是从 优惠券过来的，还是餐券过来的。
//                            if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_RICE_TICKET_OUT_ACTIVITY) {
//                                getServerDatas_for_rice_tick_history();
//                            } else if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_CARD_MAIN_ACTIVITY) {
//                                getServerDatasCardHistory();
//                            }

                            method_handler_serverDatas();

                            refreshLayout.finishLoadMore();

                        }
                    });

                }

                @Override
                public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                    refreshLayout.getLayout().post(new Runnable() {
                        @Override
                        public void run() {

                            gainDatas();

                            refreshLayout.finishRefresh();

                        }
                    });

                }
            });
        }

    }

    //点击这个条目的内容
    private void method_click_onitem(CouponCustomerVo _couponCustomerVo) {

        //携带的优惠券信息 准换，因为要序列化
        CouponCustomerVoCopy couponCustomerVoCopy = new CouponCustomerVoCopy();

        if (!ObjectUtils.isEmpty(_couponCustomerVo)) {

            couponCustomerVoCopy.setCouponId(_couponCustomerVo.getCouponId());
            couponCustomerVoCopy.setCouponCustomerId(_couponCustomerVo.getCouponCustomerId());
            couponCustomerVoCopy.setPackCustomerId(_couponCustomerVo.getPackCustomerId());
            couponCustomerVoCopy.setIsExamine(_couponCustomerVo.getIsExamine());

            //设置这个优惠券的类型是优惠券还是礼包
            int packType = _couponCustomerVo.getPackType();

            if (packType == CouponOrPackType.IS_COUPON_NOMAL.getIndex()) {

                //判断条目是优惠券还是优惠券大礼包的逻辑：
                Bundle extra_bundle = new Bundle();

                //这里是必传
                extra_bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE, auditStatus_form_tab_list);

                extra_bundle.putParcelable(ExtraKey.EXTRA_COUPONCUSTOMERVO_COPY, couponCustomerVoCopy);

                ActivityUtils.startActivity(extra_bundle, CardCouponDetailActivity.class);


            } else if (packType == CouponOrPackType.IS_COUPON_PACK.getIndex()) {

                //判断条目是优惠券还是优惠券大礼包的逻辑：
                Bundle extra_bundle = new Bundle();

                //礼包的 审核状态 也携带过去，因为要判断审核按钮的逻辑
                extra_bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE, auditStatus_form_tab_list);

                extra_bundle.putParcelable(ExtraKey.EXTRA_COUPONCUSTOMERVO_COPY, couponCustomerVoCopy);

                ActivityUtils.startActivity(extra_bundle, CardCouponPackDetailActivity.class);

            }


            //2024-2-29 10:43:48之前的老需求，不需要弹窗
//                    CommUtils.checkMaterialDialog(materialDialogCustomView);
//                    materialDialogCustomView = CommTools.function_show_dialog_seeReason(flag_jumpfrom_where, //
//                            mActivityInstance,//
//                            mActivityInstance,//
//                            couponCustomerVo, //
//                            new DoSomeThingListener() {
//                                @Override
//                                public void doSomeThing() {
//
//                                    if (materialDialogCustomView != null) {
//                                        materialDialogCustomView.dismiss();
//                                        materialDialogCustomView = null;
//                                    }
//
//                                }
//                            });

        }

    }

    @Override
    protected void initData() {
        super.initData();

        gainDatas();

    }

    @Override
    protected void gainDatas() {

        //是否有其他需要调用接口的地方；
        //这个接口内就是刷新全部内容
        pagination_upLoad = Parameterkey.pageNum_default_first;//重置

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

        if (cardToBeReviewedAdapter != null) {
            cardToBeReviewedAdapter.notifyDataSetChanged();
        }

        if (NetworkUtils.isConnected()) {

            //同时间获取卡券类型的列表
//            getServerDatasCouponType(null);

//            if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_RICE_TICKET_OUT_ACTIVITY) {
//                getServerDatas_for_rice_tick_history();
//            } else if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_CARD_MAIN_ACTIVITY) {
//                //这个次要，如果没有直接不展示也可以，但是卡券类型必须先获取为了提交数据；
//                getServerDatasCardHistory();
//            }

            method_handler_serverDatas();

        } else {

            //是否有其他的执行逻辑？
            netWorkError();
            // : 2023-08-14 15:22 添加页面遮盖，使用adapter自有的方式来填充
            setEnableLoadmore(refreshLayoutInCardFragment, false);

        }

    }

    //卡券已核销 的核销接口和 待审核-已审核 是两回事儿。
    private void getServerDatasDistHistory(int _auditStatus_form_tab_list) {

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());//,
//        map.put(Parameterkey.customerId, _customerId);//填充搜索出来的这个客户的 唯一id
        map.put(Parameterkey.pageSize, Parameterkey.pageSize_default);//,搜索关键字
        map.put(Parameterkey.pagination, pagination_upLoad);//传递的页码

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_COUPONCUSTOMERVOOUTSIDE_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getCustomerCouponForVerify_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getCustomerCouponForVerify(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
//                .compose(CardDistHistoryActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<CouponCustomerVoOutSide>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        //{"data":"","message":"无数据","code":"20002"}
                        //methodNotSuccessData(what_method, serverCode, serverMessage);

                        LogUtils.d(ConstantSign.LOGCAT_NOMAL + "handlerSomeThingNotSuccessDataForItSelf");

                        if (mDataResources != null && mDataResources.isEmpty()) {

                            setEnableLoadmore(refreshLayoutInCardFragment, false);

                            CommUtils.checkCurrently(mFragmentInstance,//
                                    serverCode,//
                                    R.drawable.errorsear,//
                                    serverMessage,//
                                    getString(R.string.nulldatanow));

                        } else {
                            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "是空的，页面没有反应");
                        }

                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {

                        loadingGone();
                        setEnableLoadmore(refreshLayoutInCardFragment, true);

                    }
                }).subscribe(new Consumer<CouponCustomerVoOutSide>() {
                    @Override
                    public void accept(CouponCustomerVoOutSide couponCustomerVoOutSide) throws Throwable {

                        method_handler_success(couponCustomerVoOutSide);

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        //页面报错；
                        function_apiException(apiException);

                    }
                });


    }

    //获取的优惠券的历史：历史记录--这个员工发放过的 优惠券 有张三-李四-王五的；
    private void getServerDatasCardHistory(int _auditStatus_form_tab_list) {

//        String keyWord_upLoad = et_searchInCustomSmall.getText().toString().trim();
//        {
//                "shopInfoId": 1495, //店铺ID
//                "auditStatus": 0, //审核状态 0：待审核 1：审核通过 2：审核不通过
//                "pagination": 1
//        }

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());

        //判断tab的标签；
        map.put(Parameterkey.auditStatus, _auditStatus_form_tab_list);

        map.put(Parameterkey.pagination, pagination_upLoad);//传递的页码
        map.put(Parameterkey.pageSize, Parameterkey.pageSize_default);//,搜索关键字

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETCUSTOMERCOUPONLISTPAGEFORMEMBER_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getCustomerCouponListPageForMember_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getPackCouponListPageForMember(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
//                .compose(CardMainActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<CouponCustomerVoOutSide>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        //methodNotSuccessData(what_method, serverCode, serverMessage);
                        // : 2023-08-15 14:32 这里还有更好的处理办法，使用BRAV自己的遮盖
//                        if (mDataResources != null && mDataResources.isEmpty()) {
//                            CommUtils.setViewGone(recyclerViewInCardMainBottom);
//                        }

                        if (mDataResources != null && mDataResources.isEmpty()) {

                            setEnableLoadmore(refreshLayoutInCardFragment, false);

                            CommUtils.checkCurrently(mFragmentInstance,//
                                    serverCode,//
                                    R.drawable.errorsear,//
                                    serverMessage,//
                                    getString(R.string.nulldatanow));

                        }

                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {

                        if (refreshLayoutInCardFragment.getState() == RefreshState.Refreshing) {
                            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "目前正处于 下拉刷新状态，所以展示  加载更多");
                            method_create_materialDialog(ConstantSign.TIPS_LOADING);
                        }

                        loadingGone();
                        setEnableLoadmore(refreshLayoutInCardFragment, true);

                    }
                }).subscribe(new Consumer<CouponCustomerVoOutSide>() {
                    @Override
                    public void accept(CouponCustomerVoOutSide couponCustomerVoOutSide) throws Throwable {

                        method_handler_success(couponCustomerVoOutSide);

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        CommUtils.checkMaterialDialog(materialDialog);

                        //页面报错；
                        if (apiException != null) {
                            if (!TextUtils.isEmpty(apiException.getDisplayMessage())) {
                                ToastUtils.showShort(apiException.getDisplayMessage());
                            }
                        }

                    }
                });
    }

    //获取餐券的历史记录，这一块和优惠券接口名不同，其他的类似
    private void getServerDatas_for_rice_tick_history() {

        //ExtraValue.VALUE_JUMP_FORM_RICE_TICKET_OUT_ACTIVITY
        //获取的优惠券的历史：历史记录--这个员工发放过的 优惠券 有张三-李四-王五的；
        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());//,
//        map.put(Parameterkey.customerId, _customerId);//填充搜索出来的这个客户的 唯一id
        map.put(Parameterkey.pagination, pagination_upLoad);//传递的页码
        map.put(Parameterkey.pageSize, Parameterkey.pageSize_default);//,搜索关键字

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETCUSTOMERCOUPONLISTPAGEFORMEMBERRICETICK_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getCustomerCouponListPageForMemberRiceTick_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getCustomerCouponListPageForMemberRiceTick(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
//                .compose(CardSumHistoryActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<CouponCustomerVoOutSide>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        //methodNotSuccessData(what_method, serverCode, serverMessage);
                        // : 2023-08-15 14:32 这里还有更好的处理办法，使用BRAV自己的遮盖

                        if (mDataResources != null && mDataResources.isEmpty()) {

                            CommUtils.checkCurrently(mFragmentInstance,//
                                    serverCode,//
                                    R.drawable.errorsear,//
                                    serverMessage,//
                                    getString(R.string.nulldatanow));

                            setEnableLoadmore(refreshLayoutInCardFragment, false);

                        }

                        // : 2023-08-14 21:20 是否要弹窗提示`

                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {

                        if (refreshLayoutInCardFragment.getState() == RefreshState.Refreshing) {

                            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "目前正处于 下拉刷新状态，所以展示  加载更多");
                            method_create_materialDialog(ConstantSign.TIPS_LOADING);

                        }

                        loadingGone();
                        setEnableLoadmore(refreshLayoutInCardFragment, true);

                    }
                }).subscribe(new Consumer<CouponCustomerVoOutSide>() {
                    @Override
                    public void accept(CouponCustomerVoOutSide couponCustomerVoOutSide) throws Throwable {

                        method_handler_success(couponCustomerVoOutSide);

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {
                        //页面报错；
                        function_apiException(apiException);
                    }

                });


    }

    //餐券和优惠券通用的处理消息过来的界面
    private void method_handler_success(CouponCustomerVoOutSide _couponCustomerVoOutSide) {

        CommUtils.checkMaterialDialog(materialDialog);

//有加载更多 不需要这样
//                        if (mDataResources != null && !mDataResources.isEmpty()) {
//                            mDataResources.clear();
//                        }

        if (_couponCustomerVoOutSide != null) {

            ArrayList<CouponCustomerVo> couponCustomerVos = _couponCustomerVoOutSide.getDataList();

            if (couponCustomerVos != null && !couponCustomerVos.isEmpty()) {
                if (mDataResources != null) {
                    mDataResources.addAll(couponCustomerVos);
                }
            }

        }

        //这里也不用管是下拉刷新或者上拉加载更多，直接判断是否为空，
        if (mDataResources != null && mDataResources.isEmpty()) {
//                            CommUtils.setViewGone(recyclerViewInCardMainBottom);
            setEnableLoadmore(refreshLayoutInCardFragment, false);
            fillNullDataView(StringUtils.getString(R.string.nulldatanow), R.drawable.errorsear);

        }

        if (cardToBeReviewedAdapter != null) {
            cardToBeReviewedAdapter.notifyDataSetChanged();
        }

        pagination_upLoad = _couponCustomerVoOutSide.getNextPagination();

        //对列表改造：
        if (pagination_upLoad == Parameterkey.GET_NEXT_PAGINATION) {
            setFinishLoadMoreWithNoMoreData(refreshLayoutInCardFragment, true);
        } else {
            setEnableLoadmore(refreshLayoutInCardFragment, true);
        }

    }

    //优惠券的发放历史的审核状态；
    private void method_gainVerifySubmitInfo_upLoad(Integer _couponCustomerId, String _couponId, Integer _auditStatus) {

//        {
//                "couponCustomerId": 62986, //发放的优惠券记录主键Id
//                "couponId": 1, //优惠券主键Id
//                "auditStatus": 1 //审核状态 0：待审核 1：审核通过 2：审核不通过
//        }

//        CardAuditStatus {
//            //审核状态 0：待审核 1：审核通过 2：审核不通过
//                    STATUS_NOT_VERIFY("0", "待审核"),
//                    STATUS_HAS_VERIFY("1", "审核通过"),
//                    STATUS_CANNOT_VERIFY("2", "审核不通过");

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.couponCustomerId, _couponCustomerId);//
        map.put(Parameterkey.couponId, _couponId);
        map.put(Parameterkey.auditStatus, CardAuditStatus.STATUS_HAS_VERIFY.getIndex());

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_UPDATEAUDITSTATUS_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.updateAuditStatus_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .updateAuditStatus(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
//                .compose(CardMainActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        if (!TextUtils.isEmpty(serverMessage)) {
                            PopTip.show(serverMessage).iconWarning();
                        }

                    }
                })).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String stringValue) throws Throwable {

                        //TipDialog.show(StringUtils.getString(R.string.add_submit_success), WaitDialog.TYPE.SUCCESS);

                        methodSubmitSuccess(mActivityInstance, new DoSomeThingListener() {
                            @Override
                            public void doSomeThing() {

                                //通知主页列表刷新
                                pagination_upLoad = Parameterkey.pageNum_default_first;

                                if (mDataResources != null && !mDataResources.isEmpty()) {
                                    mDataResources.clear();
                                }

                                if (cardToBeReviewedAdapter != null) {
                                    cardToBeReviewedAdapter.notifyDataSetChanged();
                                }

                                //------------------------------------------------------------------------------------------------------
                                method_handler_serverDatas();
                                //------------------------------------------------------------------------------------------------------

                            }
                        });

//                        methodSubmitSuccess(ConsignMainActivity.this, new DoSomeThingListener() {
//                            @Override
//                            public void doSomeThing() {
//                                //应该是仅仅刷新列表即可
//                            }
//                        });

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {
                        function_apiException(apiException);
                    }
                });
    }

    @Override
    protected int getLayoutId() {
//        return R.layout.fragment_card_push_history_list;
        return R.layout.fragment_card_tobereviewed_list;
    }

    @Override
    public void onClickNodata(View view) {

        gainDatas();

    }

    //跳转到历史记录页面
//    private void method_go_history(boolean extra_ischecked_more_items_flag, String couponPackId_upLoad) {
//
//        Bundle extra_bundle = new Bundle();
//
//        //携带是从哪个页面过去的？
//        //携带标志 是从 客户关怀过去的
//        extra_bundle.putInt(ExtraKey.EXTRA_JUMPFROM_WHERE, ExtraValue.VALUE_JUMP_FORM_CARD_MAIN_ACTIVITY);
//
//        //是否是批量审核跳转携带值内容
//        extra_bundle.putBoolean(ExtraKey.EXTRA_ISCHECKED_MORE_ITEMS_FLAG, extra_ischecked_more_items_flag);
//
//        //携带优惠券本身属于哪一个优惠券大礼包下的 优惠券大礼包id: EXTRA_COUPONPACKID_UPLOAD
//        extra_bundle.putString(ExtraKey.EXTRA_COUPONPACKID_UPLOAD, couponPackId_upLoad);
//
//        ActivityUtils.startActivity(extra_bundle, CardSumHistoryActivity.class);
//
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThreadInCardMain(EventCardMain eventCardMain) {

        if (eventCardMain != null) {

            if (eventCardMain.getMessage() == ExtraValue.EVENTBUS_EVENT_TO_REFRESH_CARD_MAIN_LIST) {

                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "收到刷新主页历史记录列表的消息--EVENTBUS_EVENT_TO_REFRESH_CARD_MAIN_LIST");

                //如果发起搜索，要重置 第1页
                pagination_upLoad = Parameterkey.pageNum_default_first;

                //清空历史数据
                if (mDataResources != null && !mDataResources.isEmpty()) {
                    mDataResources.clear();
                }

                if (cardToBeReviewedAdapter != null) {
                    cardToBeReviewedAdapter.notifyDataSetChanged();
                }


                method_handler_serverDatas();

            }

        }

    }


    private void method_handler_serverDatas() {

        //------------------------------------------------------------------------------------------------------
        //审核完毕刷新当前列表。
        if (auditStatus_form_tab_list == CouponAuditStatus.AUDITSTATUS_TO_BE_REVIEWED.getIndex()//待审核
                || auditStatus_form_tab_list == CouponAuditStatus.AUDITSTATUS_REVIEWED.getIndex()//已审核-审核通过
                || auditStatus_form_tab_list == CouponAuditStatus.AUDITSTATUS_REVIEWE_NOT_PASS.getIndex()//
        ) {

            getServerDatasCardHistory(auditStatus_form_tab_list);

        } else if (auditStatus_form_tab_list == CouponAuditStatus.AUDITSTATUS_HAS_DIST.getIndex()) {

            //已核销的就用【已核销的历史记录接口】和这些页面不同。
            getServerDatasDistHistory(auditStatus_form_tab_list);

        }

        //------------------------------------------------------------------------------------------------------
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

        if (cardToBeReviewedAdapter != null) {
            cardToBeReviewedAdapter.notifyDataSetChanged();
            cardToBeReviewedAdapter = null;
        }

        if (mDataResources != null) {
            mDataResources = null;
        }

//        CommUtils.checkMaterialDialog(materialDialogCustomView);

        EventBus.getDefault().unregister(this);

    }


}